package com.example.capsule.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.*;
import java.util.*;

@RestController
@RequestMapping("/api/upload")
public class FileUploadController {

    @Value("${spring.servlet.multipart.location}")
    private String uploadPath;

    @PostMapping
    public Map<String, String> upload(@RequestParam("image") MultipartFile image) throws IOException {
        if (image.isEmpty() || !Objects.requireNonNull(image.getContentType()).startsWith("image/"))
            throw new RuntimeException("文件为空或不是图片");

        String ext = image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf('.'));
        String fileName = UUID.randomUUID() + ext;
        Path path = Paths.get(uploadPath);
        Files.createDirectories(path);
        Path filePath = path.resolve(fileName);
        image.transferTo(filePath.toFile());

        // 静态资源可直接访问 /upload/xxx
        String url = "/upload/" + fileName;
        return Map.of("url", url);
    }
}